package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

/**
 * @author SunSun
 * @date 2021/10/31
 */
@DubboService
public class UserLocationApiImpl implements UserLocationApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public boolean updateLocation(Long userId, Double longitude, Double latitude, String address) {
        try {
            Query query=Query.query(Criteria.where("userId").is(userId));
            UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
            if(location==null){
                location=new UserLocation();
                location.setUserId(userId);
                location.setAddress(address);
                location.setCreated(System.currentTimeMillis());
                location.setUpdated(System.currentTimeMillis());
                location.setLastUpdated(System.currentTimeMillis());
                location.setLocation(new GeoJsonPoint(longitude,latitude));
                mongoTemplate.save(location);
            }else {
                Update update=Update.update("location",new GeoJsonPoint(longitude,latitude))
                        .set("updated",System.currentTimeMillis())
                        .set("lastUpdated",location.getUpdated())
                        .set("address",address);
                mongoTemplate.updateFirst(query, update, UserLocation.class);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public List<Long> queryNearUser(Long userId, Double aDouble) {
        Criteria criteria=Criteria.where("userId").is(userId);
        UserLocation location = mongoTemplate.findOne(Query.query(criteria), UserLocation.class);
        if(location==null){
            return null;
        }
        GeoJsonPoint geoJsonPoint=location.getLocation();
        Distance distance=new Distance(aDouble/1000,Metrics.KILOMETERS);
        Circle circle=new Circle(geoJsonPoint,distance);
        Query query=Query.query(Criteria.where("location").withinSphere(circle));
        List<UserLocation> userLocations = mongoTemplate.find(query, UserLocation.class);
        return CollUtil.getFieldValues(userLocations,"userId",Long.class);
    }
}
